package com.android.matmanual;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

public class GpsTest extends Activity {
	private static final String TAG = "GpsTest";
	TextView mGpsInfo;
	TextView mGpsStrength;
	WakeLock mWakeLock;
	LocationManager mLocationManager;
	boolean flagmodify;
	LocationListener mLocationListener;
	GpsStatus.Listener mGpsStatusListener;
	Thread mgpscheck;
	public final static int GPS_ENABLED = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.gps_test);
		setTitle(R.string.gps_test);
		PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
				"XYTEST");
		mWakeLock.acquire();
		mGpsInfo = (TextView) findViewById(R.id.gps_info);
		mGpsStrength = (TextView) findViewById(R.id.gps_strength);

		mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

			if (Const.DEBUG) {
				Log.e(TAG, "helye Gps is off ");
				Toast.makeText(this, "GPS没有打开，请先打开GPS", Toast.LENGTH_LONG)
						.show();
			}
			/*
			 * Settings.Secure.setLocationProviderEnabled(getContentResolver(),
			 * LocationManager.GPS_PROVIDER, true);
			 */

			changeGPSstatu();// Kitkat版本之前此自动打开GPS功能有效。

			flagmodify = true;
		} else {
			Log.e(TAG, "helye Gps is on ");
			Toast.makeText(this, "GPS已经打开", Toast.LENGTH_SHORT).show();
		}

		mgpscheck = new Thread(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub

				while (!mLocationManager
						.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (Const.DEBUG) {
					Log.e(TAG, "helye mgpscheck run ");
					gpsHandler.sendEmptyMessageDelayed(GPS_ENABLED, 100);
				}
			}
		});

		if (FeatureSwitcher.isGpsSupport())
			mgpscheck.start();
		else
			mGpsStrength.setText(this.getString(R.string.GPS_not_support));

	}

	Handler gpsHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == GPS_ENABLED) {
				Criteria criteria = new Criteria();
				Log.e(TAG, "helye GPS_ENABLED 1111111 ");
				criteria.setAccuracy(Criteria.ACCURACY_FINE); // 锟竭撅拷锟斤拷
				criteria.setAltitudeRequired(false);
				criteria.setBearingRequired(false);
				criteria.setCostAllowed(true);
				criteria.setPowerRequirement(Criteria.POWER_LOW); // 锟酵癸拷锟斤拷
				String provider = mLocationManager.getBestProvider(criteria,
						true); // 锟斤拷取GPS锟斤拷息
				Location location = mLocationManager
						.getLastKnownLocation(provider); // 通锟斤拷GPS锟斤拷取位锟斤拷
				updateToNewLocation(location);
				mLocationListener = new LocationListener() {

					public void onLocationChanged(Location arg0) {
						// TODO Auto-generated method stub
						updateToNewLocation(arg0);
					}

					public void onProviderDisabled(String arg0) {
						// TODO Auto-generated method stub
						Location location = mLocationManager
								.getLastKnownLocation(arg0);
						updateToNewLocation(location);
					}

					public void onProviderEnabled(String arg0) {
						// TODO Auto-generated method stub

						updateToNewLocation(null);

					}

					public void onStatusChanged(String arg0, int arg1,
							Bundle arg2) {
						// TODO Auto-generated method stub

						// TODO Auto-generated method stub
						switch (arg1) {
						// GPS状态为锟缴硷拷时
						case LocationProvider.AVAILABLE:
							break;
						case LocationProvider.OUT_OF_SERVICE:
							break;
						case LocationProvider.TEMPORARILY_UNAVAILABLE:
							break;
						}

					}

				};
				mLocationManager.requestLocationUpdates(provider, 1 * 200, 100,
						mLocationListener);

				mGpsStatusListener = new GpsStatus.Listener() {

					public void onGpsStatusChanged(int arg0) {
						// TODO Auto-generated method stub
						switch (arg0) {
						case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
							GpsStatus gpsStatus = mLocationManager
									.getGpsStatus(null);
							String sBuildNumber = "";
							int i = 0;
							// 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟绞撅拷锟斤拷锟斤拷逊锟斤拷值锟斤拷锟斤拷呛锟斤拷锟斤拷锟斤拷拥锟斤拷锟斤拷呛锟斤拷锟斤拷堑锟絇rn,Snr
							for (GpsSatellite gpsSatellite : gpsStatus
									.getSatellites()) {
								i++;
								sBuildNumber = sBuildNumber
										+ getResources().getString(
												R.string.signal_strength) + ":"
										+ gpsSatellite.getSnr() + "\n";
							}
							mGpsStrength.setText(sBuildNumber);
							break;
						default:
							break;
						}
					}
				};
				mLocationManager.addGpsStatusListener(mGpsStatusListener);

			}
		}
	};

	private void changeGPSstatu() {
		Intent intent = new Intent();
		intent.setClassName("com.android.settings",
				"com.android.settings.widget.SettingsAppWidgetProvider");
		intent.addCategory("android.intent.category.ALTERNATIVE");
		intent.setData(Uri.parse("custom:3"));
		try {
			PendingIntent.getBroadcast(this, 0, intent, 0).send();
			// sendBroadcast(intent);
		} catch (CanceledException e) {
			e.printStackTrace();
		}
	}

	// 跳转到GPS打开界面
	private void EntryGpsDisplay() {
		Intent intent = new Intent(
				android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// startActivityForResult(intent,0);
		try {
			startActivityForResult(intent, 0);
		} catch (ActivityNotFoundException e) {
			Log.e(TAG, "startActivity() failed: " + e);
		}
	}

	private void updateToNewLocation(Location location) {

		if (location != null) {
			StringBuilder sb = new StringBuilder();
			/*double latitude = location.getLatitude();
			double longitude = location.getLongitude();*/
			
			sb.append("实时的位置信息：\n"); 
			sb.append("经度：");
			sb.append(location.getLongitude());
			sb.append("\n纬度：");
			sb.append(location.getLatitude());
			sb.append("\n高度：");
			sb.append(location.getAltitude());
			sb.append("\n速度："); 
			sb.append(location.getSpeed());
			sb.append("\n方向："); 
			sb.append(location.getBearing());
			mGpsInfo.setText(sb.toString()); 
		
			/*mGpsInfo.setText(getResources().getString(R.string.gps_latitude)
					+ ":" + latitude + "\n"
					+ getResources().getString(R.string.gps_longitude) + ":"
					+ longitude);*/
			if (Const.DEBUG) {
				Log.e(TAG, "helye show GPS information----------");
				Toast.makeText(this, "显示GPS卫星信号信息", Toast.LENGTH_SHORT).show();
			}
		} else {
			mGpsInfo.setText(R.string.gps_prompt);
			if (Const.DEBUG) {
				Log.e(TAG, "helye show GPS searching....");
				Toast.makeText(this, "搜索GPS卫星信号...", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		int result = TestControl.GetKeyEvent(keyCode);
		if (result != TestControl.DO_NOTHING) {
			setResult(result);
			finish();
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (Const.DEBUG) {
			Log.e(TAG, "helye close GPS TEST");
			// Toast.makeText(this, "关闭GPS测试",Toast.LENGTH_SHORT).show();
		}
		changeGPSstatu();
		if (mWakeLock != null) {
			mWakeLock.release();
			mWakeLock = null;
		}
		gpsHandler.removeMessages(GPS_ENABLED);
		if (mLocationListener != null) {
			mLocationManager.removeUpdates(mLocationListener);
		}
		if (mGpsStatusListener != null) {
			mLocationManager.removeGpsStatusListener(mGpsStatusListener);
		}
		if (flagmodify == true) {
			Settings.Secure.setLocationProviderEnabled(getContentResolver(),
					LocationManager.GPS_PROVIDER, false);
		}

		super.onDestroy();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		finish();
		super.onStop();
	}

	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	}

}
